package com.activities;


import java.io.File;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.adaptadores.LugaresThumbAdapter;
import com.callbacks.Callbacks.LCompleted;
import com.callbacks.InterfaceLugares;
import com.clases.Categoria;
import com.clases.Lugar;
import com.constantes.AppConstant;
import com.constantes.Constantes;
import com.example.santiagotur.R;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.util.CoverManager;
import com.util.Utils;


public class Paginaprincipal extends FragmentActivity implements InterfaceLugares {

    private LugaresThumbAdapter adapter;

    private ImageView Boton_categorias;

    private ImageView Busqueda_Lugar;

    private final int Categoria = 0;

    private int columnWidth;

    private GridView gridView;

    private Boolean isInicio = true;

    private LinearLayout Linear_Scroll_MeEva;

    private boolean portadaStarted = false;

    private SlidingMenu sMenu;

    private TextView titulo_mejore_evaluados;

    private TextView titulo_mejores_lugares;

    private TextView Titulo_noticias;

    public void getLugaresCategorias(int idCategoria) {

        sMenu.toggle();

        adapter.clear();
        Log.e("ID", "" + idCategoria);
        if (idCategoria == 0) {

            adapter = null;
            gridView.setAdapter(null);
            getLugares(0);

        }
        else
            isInicio = false;

        Lugar lg = new Lugar(this);
        lg.setCallbackLugar(new LCompleted() {

            @Override
            public void Completed(Lugar[] result) {

                procesarLugares(result);

            }
        });

        Categoria cat = new Categoria();
        cat.setIDCategoria(idCategoria);
        lg.setCategoria(cat);
        lg.setLast(0);
        lg.execute(Constantes.ACCION_LUGAR_GET_CATEGORIA);

    }

    private void config(Context context) {

        File cacheDir = new File(Environment.getExternalStorageDirectory().getAbsoluteFile()
                    + "SantiagoTur/");

        if (!cacheDir.exists())
            cacheDir.mkdir();

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).threadPoolSize(3) // default
        .threadPriority(Thread.NORM_PRIORITY - 2) // default
        .tasksProcessingOrder(QueueProcessingType.FIFO) // default
        .writeDebugLogs().denyCacheImageMultipleSizesInMemory().discCache(new UnlimitedDiscCache(cacheDir)) // default
        .build();

        if (ImageLoader.getInstance().isInited())
            ImageLoader.getInstance().destroy();

        ImageLoader.getInstance().init(config);
    }

    

    private void inicializar() {

        config(this);

        sMenu = new CreateSliderClass(this).Create();

        Titulo_noticias = (TextView) findViewById(R.id.title_actionbar_main);
        Boton_categorias = (ImageView) findViewById(R.id.open_categoria);
        //
        Boton_categorias.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                CreateSliderClass.Menu.toggle();

            }
        });
        //
        gridView = (GridView) findViewById(R.id.gridView_MejorLugar);
        Busqueda_Lugar = (ImageView) findViewById(R.id.Busqueda_Lugares);
        //
        Busqueda_Lugar.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent intent = new Intent(v.getContext(), Busqueda_lugar.class);
                v.getContext().startActivity(intent);

            }
        });

        initilizeGridLayout();

        getLugares(0);

    }

    private void iniciarPortadas(Lugar[] lugares) {

        if (!portadaStarted) {
            new CoverManager(lugares, (ImageView) findViewById(R.id.imaportada)).startChecking();
            portadaStarted = true;
        }

    }

    private void initilizeGridLayout() {

        Resources r = getResources();
        float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, AppConstant.GRID_PADDING, r.getDisplayMetrics());

        Utils utils = new Utils(this);
        columnWidth = (int) ((utils.getScreenWidth() - ((AppConstant.NUM_OF_COLUMNS + 1) * padding)) / AppConstant.NUM_OF_COLUMNS);

        gridView.setNumColumns(AppConstant.NUM_OF_COLUMNS);
        gridView.setColumnWidth(columnWidth);
        gridView.setStretchMode(GridView.NO_STRETCH);
        gridView.setPadding((int) padding, (int) padding, (int) padding, (int) padding);
        gridView.setHorizontalSpacing((int) padding);
        gridView.setVerticalSpacing((int) padding);

    }

    private void procesarLugares(Lugar[] result) {

        if (adapter == null) {
            adapter = new LugaresThumbAdapter(this, columnWidth,this);
            gridView.setAdapter(adapter);
        }

        for (Lugar lg : result) {
            adapter.add(lg);

        }

        adapter.notifyDataSetChanged();

        //

        iniciarPortadas(result);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_principal);
        inicializar();
    }

    @Override
    protected void onResume() {

        super.onResume();
    }

	@Override
	public void getLugares(int last) {
		  Lugar lg = new Lugar(this);
	        lg.setCallbackLugar(new LCompleted() {

	            @Override
	            public void Completed(Lugar[] result) {

	                procesarLugares(result);

	            }
	        });

	        lg.setLast(last);
	        lg.execute(Constantes.ACCION_LUGAR_GET_INICIO);
		
	}

}
